package book.controller;

import book.pojo.Reader;
import book.pojo.vo.ReaderVO;
import book.service.IReaderService;
import book.service.impl.IReaderServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/reader")
public class ReaderController extends BaseController{
    private BookController bookController = new BookController();
    private IReaderService readerService = new IReaderServiceImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、取得传来的登录信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //int role        = Integer.parseInt(req.getParameter("role"));
        int rememberMe  = Integer.parseInt(req.getParameter("rememberMe"));
        //验证码
        String checkCode= req.getParameter("checkCode");

        //*********判断验证码是否正确开始**********//

        //取出会话中预先存储的验证码
        String checkCodeSession = (String)req.getSession().getAttribute("CHECKCODE_SERVER");
        //判断验证码是否正确
        if(checkCodeSession == null || !checkCodeSession.equalsIgnoreCase(checkCode)) {
            req.setAttribute("msg","验证码不正确");
            System.out.println("验证码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }

        //*********判断验证码是否正确结束**********//

        //创建User封装登录信息
        ReaderVO readerVO = new ReaderVO();
        System.out.println("username: "+username);
        System.out.println("password: "+password);
        readerVO.setUsername(username);
        readerVO.setPassword(password);

        //2、调用业务对象执行登录验证
        Reader loginReader = readerService.login(readerVO);

        //3、处理登录结果
        if(null == loginReader){
            //登录失败，登录id或者密码错误
            req.setAttribute("msg","登录失败，登录名或者密码错误！");
            //请求转发
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else{
            //登录成功
            //1、在会话中维持登录状态
            req.getSession().setAttribute("username",loginReader.getUsername());
            req.getSession().setAttribute("name",loginReader.getName());
            //2、处理记住登录状态
            if(rememberMe > 0){
                //基于Cookie来记住登录状态
                Cookie cookie = new Cookie("rememberMe",loginReader.getUsername());
                //设置Cookie的最大存活期
                cookie.setMaxAge(rememberMe*24*60*60);
                //将cookie添加到响应对象中
                resp.addCookie(cookie);
                System.out.println("cookie对象已经添加");
            }
            //3、跳转首页
            bookController.findAllBooks(req,resp);
            System.out.println("已跳转首页");
        }
    }
    //用户注销
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //让会话失效
        req.getSession().invalidate();

        Cookie cookie = new Cookie("rememberMe","xxx");
        //删除Cookie
        cookie.setMaxAge(0);
        resp.addCookie(cookie);

        //请求重定向到登录页面
        resp.sendRedirect("login.jsp");
    }
    //注册
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //创建User对象
            Reader reader = new Reader();
            //req.getParameterMap()：获取请求传参的map对象
            //populate方法：自动将map取出填充到userVO对象中
            BeanUtils.populate(reader,req.getParameterMap());

            /*****处理验证码是否正确******/
            //取出会话中的验证码
            String checkCodeSession = (String)req.getSession().getAttribute("CHECKCODE_SERVER");
            if(!reader.getCheckCode().equalsIgnoreCase(checkCodeSession)){
                req.setAttribute("msg","验证码错误");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            }

            //调用业务对象实现注册--就是添加一个用户
            int row = readerService.addReader(reader);
            req.setAttribute("msg",row==1?"注册成功！":"注册失败！");
            //处理结果：跳转登录页面
            if(row==1){
                //注册成功，跳转登录页面
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        } catch (Exception e) {
            //发生异常，注册失败,跳转错误页面
            e.printStackTrace();
            req.setAttribute("msg","注册失败，错误原因："+e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req,resp);
        }
    }

}
